// src/Browsing.tsx
import { useState, useEffect } from 'react';
import { Card, List, Typography, Button, Spin, Pagination, message, Popconfirm, Tooltip, Switch } from 'antd';
import { EyeOutlined, DeleteOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Text } = Typography;

interface BrowseRecord {
  id: number;
  user: {
    id: number;
    username: string;
    avatar?: string;
  };
  recipeId: number;
  createdAt: string;
  recipe: {
    id: number;
    title: string;
    coverImage: string;
    duration: number;
    difficulty: number;
    likesCount: number;
    favoriteCount: number;
    description: string;
  };
}

interface BrowsingProps {
  userId: number;
  showAll?: boolean;
  onShowAllChange?: (showAll: boolean) => void;
}

function Browsing({ userId, showAll = false, onShowAllChange }: BrowsingProps) {
  const navigate = useNavigate();
  const [browseRecords, setBrowseRecords] = useState<BrowseRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [deleteMode, setDeleteMode] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const pageSize = 8;

  const getImageUrl = (coverImage: string) => {
    if (!coverImage) {
      return 'https://via.placeholder.com/300x200?text=菜品图片';
    }
    if (coverImage.startsWith('http')) {
      return coverImage;
    }
    return `http://218.244.141.86:8080${coverImage}`;
  };

  const fetchBrowseRecords = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/browse/user/${userId}`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const recordsData: BrowseRecord[] = await response.json();
        const sortedRecords = recordsData.sort((a, b) => 
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        );
        setBrowseRecords(sortedRecords);
      } else {
        console.warn('获取浏览记录失败:', response.status);
        message.error('获取浏览记录失败');
        setBrowseRecords([]);
      }
    } catch (error) {
      console.error('获取浏览记录失败:', error);
      message.error('网络错误，请检查连接');
      setBrowseRecords([]);
    } finally {
      setLoading(false);
    }
  };

  const deleteBrowseRecord = async (recordId: number) => {
    setDeletingId(recordId);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/browse/${recordId}?userId=${userId}`, {
        method: 'DELETE',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        message.success('删除成功');
        fetchBrowseRecords();
      } else {
        message.error('删除失败');
      }
    } catch (error) {
      console.error('删除浏览记录失败:', error);
      message.error('删除失败，请检查网络');
    } finally {
      setDeletingId(null);
    }
  };

  useEffect(() => {
    if (userId) {
      fetchBrowseRecords();
    }
  }, [userId]);

  const handleToggleShowAll = () => {
    if (onShowAllChange) {
      onShowAllChange(!showAll);
    }
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const displayedRecords = showAll 
    ? browseRecords.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    : browseRecords.slice(0, 4);

  const totalRecords = browseRecords.length;

  return (
    <Card 
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <EyeOutlined style={{ color: '#52c41a' }} />
          <span>浏览历史 {showAll && `(${totalRecords})`}</span>
        </div>
      } 
      extra={
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          {/* 删除模式切换 */}
          {browseRecords.length > 0 && (
            <Tooltip title={deleteMode ? "退出删除模式" : "进入删除模式"}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                <DeleteOutlined style={{ color: deleteMode ? '#ff4d4f' : '#999' }} />
                <Switch 
                  size="small" 
                  checked={deleteMode}
                  onChange={setDeleteMode}
                />
              </div>
            </Tooltip>
          )}
          
          {/* 查看更多按钮 - 固定显示 */}
          {browseRecords.length > 0 && (
            <Button 
              type="link" 
              style={{ color: '#e8d9c7', fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '4px' }}
              onClick={handleToggleShowAll}
            >
              {showAll ? (
                <>
                  <UpOutlined />
                  收起
                </>
              ) : (
                <>
                  <DownOutlined />
                  查看更多
                </>
              )}
            </Button>
          )}
        </div>
      }
      style={{
        background: 'rgba(255, 253, 248, 0.9)',
        border: '1px solid #e8d5b5',
        borderRadius: '12px',
        marginBottom: '24px'
      }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
          <div style={{ marginTop: 10, color: '#8b4513' }}>加载浏览记录中...</div>
        </div>
      ) : browseRecords.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无浏览记录
        </div>
      ) : (
        <>
          <List
            grid={{ gutter: 16, column: showAll ? 4 : 4 }}
            dataSource={displayedRecords}
            renderItem={record => (
              <List.Item>
                <Card
                  hoverable
                  style={{
                    background: 'white',
                    borderRadius: '8px',
                    border: '1px solid #f0e6d2'
                  }}
                  cover={
                    <div style={{ position: 'relative', display: 'block' }}>
                      <img 
                        alt={record.recipe.title} 
                        src={getImageUrl(record.recipe.coverImage)}
                        style={{ 
                          height: '150px', 
                          width: '100%',
                          objectFit: 'cover',
                          cursor: deleteMode ? 'default' : 'pointer',
                          display: 'block'
                        }}
                        onClick={() => !deleteMode && navigate(`/recipe/${record.recipe.id}`, { state: { recipe: record.recipe } })}
                        onError={(e) => {
                          e.currentTarget.src = 'https://via.placeholder.com/300x200?text=菜品图片';
                        }}
                      />
                      {/* 删除按钮 - 在删除模式下显示 */}
                      {deleteMode && (
                        <Popconfirm
                          title="确定要删除这条浏览记录吗？"
                          onConfirm={() => deleteBrowseRecord(record.id)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button
                            type="primary"
                            danger
                            icon={<DeleteOutlined />}
                            loading={deletingId === record.id}
                            style={{
                              position: 'absolute',
                              top: 8,
                              right: 8,
                            }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            删除
                          </Button>
                        </Popconfirm>
                      )}
                    </div>
                  }
                >
                  <Text strong style={{ color: '#8b4513' }}>{record.recipe.title}</Text>
                  <div style={{ marginTop: '8px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
                      <span>收藏 {record.recipe.favoriteCount || 0}</span>
                    </div>
                    {record.recipe.description && (
                      <div style={{ marginTop: '4px' }}>
                        <Text 
                          type="secondary" 
                          style={{ 
                            fontSize: '11px', 
                            display: '-webkit-box',
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: 'vertical',
                            overflow: 'hidden'
                          }}
                        >
                          {record.recipe.description}
                        </Text>
                      </div>
                    )}
                  </div>
                </Card>
              </List.Item>
            )}
          />
          {showAll && totalRecords > pageSize && (
            <div style={{ textAlign: 'center', marginTop: '20px' }}>
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={totalRecords}
                onChange={handlePageChange}
                showSizeChanger={false}
              />
            </div>
          )}
        </>
      )}
    </Card>
  );
}

export default Browsing;